/*
 * @Author: zhangwei 1405298045@qq.com
 * @Date: 2022-03-03 21:56:09
 * @LastEditTime: 2022-03-04 11:43:33
 * @LastEditors: zhangwei 1405298045@qq.com
 * @Description:
 * @FilePath: /ll-fe-mp-dyfx/src/utils/srorage/crypto.js
 *
 */
import CryptoJS from 'crypto-js';
import { storageEncryptionKey } from '@/config/base';

/**
 * 加密
 * @param {*} params
 * @param {*} otherParams
 * @returns
 */
export const Encrypt = (params, otherParams = {}) => {
	if (typeof params !== 'string') {
		params = JSON.stringify(params);
	}

	const { key = storageEncryptionKey, iv = storageEncryptionKey } = otherParams;

	const Storage_Key = CryptoJS.enc.Utf8.parse(key);
	const Storage_Iv = CryptoJS.enc.Utf8.parse(iv);

	const formatParams = CryptoJS.enc.Utf8.parse(params);
	const encrypted = CryptoJS.AES.encrypt(formatParams, Storage_Key, {
		iv: Storage_Iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7
	});

	return encrypted.ciphertext.toString().toUpperCase();
};

/**
 * 解密
 * @param {} params
 * @param {*} otherParams
 * @returns
 */
export const Decrypt = (params, otherParams = {}) => {
	const encryptedHexStr = CryptoJS.enc.Hex.parse(params);

	const { key = storageEncryptionKey, iv = storageEncryptionKey } = otherParams;

	const Storage_Key = CryptoJS.enc.Utf8.parse(key);
	const Storage_Iv = CryptoJS.enc.Utf8.parse(iv);

	const formatParams = CryptoJS.enc.Base64.stringify(encryptedHexStr);
	const decrypt = CryptoJS.AES.decrypt(formatParams, Storage_Key, {
		iv: Storage_Iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7
	});

	const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);

	return decryptedStr.toString();
};
